<?php

class User_Service{

	protected $userModel;
	protected $wxAccountModel;

	public function __construct(){
		$this->userModel = new User_Model();
		$this->wxAccountModel = new WxAccount_Model();
	}

	public function check($email,$password){
		$user = $this->userModel->getByEmail($email);
		if (null===$user) {
			return false;
		}else{
			$passwd = $user->getPasswd();
			if (md5($password)!==$passwd) {
				return false;
			}else{
				return $user;
			}
		}
	}

	public function addUser($email,$passwd1,$passwd2){
		if (empty($email)||empty($passwd1)||empty($passwd2)) {
			throw new Pfinal_Exception_Runtime("invalid email or password");
		}
		if ($passwd1!==$passwd2) {
			throw new Pfinal_Exception_Runtime("password not match");
		}
		$id = null;
		try{
			$id = $this->userModel->addUser($email, $passwd1);
		}catch(Exception $ex){
			throw new Pfinal_Exception_Runtime($ex->getMessage(),$ex->getCode());
		}
		return $id;
	}

	/**
	 * [addWxAccount description]
	 * @param [type] $userId   [description]
	 * @param [type] $account  [description]
	 * @param [type] $password [description]
	 */
	public function addWxAccount($userId,$account,$password){
		try{
			$this->wxAccountModel->addWxAccount($userId,$account,$password);
		}catch(Exception $ex){
			throw new Pfinal_Exception_Runtime($ex->getMessage(),$ex->getCode());
		}
	}

	public function getWxAccountList($userId){
		$accountList =  $this->wxAccountModel->getAll($userId);
		$ret = array();
		if (!empty($accountList)) {
			foreach ($accountList as $account) {
				$ret[] = array('id'=>$account->id,'name'=>$account->account,'password'=>$account->password);
			}
		}
		return $ret;
	}
}